#!/usr/bin/bash

# Intel GPUs need the GSK_RENDERER set to gl to avoid graphical glitches with GTK4/libadwaita applications
# This script dynamically detects if such a gpu is present by checking if the xe module or the i915 module is to then apply the workaround.
# and then remove the workaround, if it is applied but the xe or i915 module is not loaded (thereby no affected gpu is in use)
write_intel_gtk_fix() {
    # Set GSK_RENDERER to gl for the user
    mkdir -p "$HOME/.config/environment.d"
    echo "GSK_RENDERER=gl" > "$HOME/.config/environment.d/intel-gtk-fix.conf"
}

if lsmod | grep -P "^(xe|i915) " > /dev/null && [ ! -f "$HOME/.config/environment.d/intel-gtk-fix.conf" ]; then
    # User is using an Intel GPU
    write_intel_gtk_fix
elif ! lsmod | grep -P "^(xe|i915) " > /dev/null && [ -f "$HOME/.config/environment.d/intel-gtk-fix.conf" ]; then
    # Remove the env var file as no intel gpu is being used.
    rm "$HOME/.config/environment.d/intel-gtk-fix.conf"
fi
